package dp05.leertaak1.dao.implementations;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.StringTokenizer;

import dp05.leertaak1.dao.definitions.DAO;

public class CsvDAO extends DAO
{
    private final String FILENAME = "sequence.csv";
    BufferedReader reader;
    PrintWriter writer;
    File csvFile;

    private CsvDAO()
    {
        super();
        csvFile = loadFile(FILENAME);
    }

    private File loadFile(String name)
    {
        File file = new File(name);
        if (!file.exists())
        {
            try
            {
                file.createNewFile();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        return file;

    }

    @Override
    public LinkedList<Integer> get()
    {
        dataStructure.clear();

        try
        {
            reader = new BufferedReader(new FileReader(csvFile));
        } catch (FileNotFoundException e1)
        {
            e1.printStackTrace();
        }
        
        String line = null;

        try
        {
            while ((line = reader.readLine()) != null)
            {
                StringTokenizer st = new StringTokenizer(line, ",");
                while (st.hasMoreTokens())
                {
                    int element = Integer.parseInt(st.nextToken());
                    dataStructure.add(element);
                }
            }
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return dataStructure;
    }

    public static DAO getInstance()
    {
        if (instance == null)
        {
            synchronized (RdbDAO.class)
            {
                if (instance == null)
                {
                    instance = new CsvDAO();
                }
            }
        }
        return instance;
    }

    public void update()
    {
        csvFile = loadFile(FILENAME);
        try
        {
            writer = new PrintWriter(csvFile);
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

        for (int i = 0; i < dataStructure.size(); i++)
        {
            Integer number = dataStructure.get(i);
            writer.write(number.toString());
            if (i < dataStructure.size() - 1)
            {
                writer.write(',');
            }
        }
        writer.flush();
    }

}
